package com.chixing.controller;


import com.chixing.entity.*;
import com.chixing.entity.vo.CarAddress;
import com.chixing.service.CarESService;
import com.chixing.service.IBusinessOutletsService;
import com.chixing.service.ICarService;
import com.chixing.util.Result;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shy
 * @since 2022-10-20
 */
@Controller
@RequestMapping("/car")
public class CarController {
    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private ICarService carServiceImpl;
    @Autowired
    private IBusinessOutletsService businessOutletsServiceImpl;

    @Resource
    private CarESService carESService;

    @Resource
    private ICarService iCarService;

    //得到所有车辆列表
    @GetMapping("/carAllList")
    @ResponseBody
    public Result searchAllCar(){
        Result result = carServiceImpl.getAllCar();
        return result;
    }

    //得到选定门店位置车辆列表
    @GetMapping("/carList/{outletName}")
    public ModelAndView searchCarByOutletsName(@PathVariable("outletName") String name){
        CarAddress carAddress = new CarAddress();

        BusinessOutlets businessOutlets = businessOutletsServiceImpl.getBusinessOutletByName(name);
        carAddress.setBusinessOutlets(businessOutlets);

        List<Car> carList = carServiceImpl.getCarByOutletsName(name);
        carAddress.setCarList(carList);

        System.out.println("车辆列表:"+carList);
        System.out.println("门店："+businessOutlets);
        System.out.println("封装后的carAddress对象:"+carAddress);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("carList",carList);
        modelAndView.addObject("carAddress",carAddress);
        modelAndView.setViewName("vehicle/vehicle_screening");
        return modelAndView;
    }

    //根据id查询车辆详情
    @GetMapping("/{id}")
    public ModelAndView getCarById(@PathVariable("id") Integer carId){
        Car car = carServiceImpl.getByCarId(carId);
        System.out.println("car: "+car);
        BusinessOutlets businessOutlet = businessOutletsServiceImpl.getById(car.getOther2());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("car",car);
        modelAndView.addObject("businessOutlet",businessOutlet);

        modelAndView.setViewName("myOrder/myorder_submit");
        return modelAndView;
    }

    //封装数据进入list传入es中
    @GetMapping("/savecar")
    public String getList(){
        ArrayList<CarES> arrayList = new ArrayList<>();
        List<Car> list = iCarService.list();
        for (Car car : list) {
            CarES cares = new CarES();
            cares.setCarCardId(car.getCarCardId());
            cares.setCarCase(car.getCarCase());
            cares.setCarCharger(car.getCarCharger());
            cares.setCarColor(car.getCarColor());
            cares.setCarDisplacement(car.getCarDisplacement());
            cares.setCarId(car.getCarId());
            cares.setCarImgId(car.getCarImgId());
            cares.setCarName(car.getCarName());
            cares.setCarPrice(car.getCarPrice());
            cares.setCarSeat(car.getCarSeat());
            cares.setCarStatus(car.getCarStatus());
            cares.setCayTypeId(car.getCayTypeId());
            cares.setCreatetime(car.getCreatetime());
            cares.setUpdatetime(car.getUpdatetime());
            cares.setOther1(car.getOther1());
            cares.setOther2(car.getOther2());
            cares.setVersion(car.getVersion());
            arrayList.add(cares);
            carESService.save(cares);
        }
//        carESService.saveAll(arrayList);
        System.out.println(arrayList);
        return  "ok";
    }




    // es高亮查询并进行分词
    @GetMapping("/getDataByName/{carName}")
    // @ResponseBody
    public  ModelAndView  getHighByCarName(@PathVariable("carName") String carName){
        System.out.println("carName = " + carName);
        //根据一个值查询多个字段，并高亮显示，这里的查询是取并集，
        //即多个字段只要有一个字段满足即可

        //需要查询的字段
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("carName",carName));


        //构建高亮查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withHighlightFields(  new HighlightBuilder.Field("carName"))
                .withHighlightBuilder(new HighlightBuilder()
                        .preTags("<span style='color:red'>")
                        .postTags("</span>"))
                .build();

        //查询
        SearchHits<CarES> search = restTemplate.search(searchQuery,CarES.class);
//  SearchHits<User> ==== for(...user ) -- high light name : old name ,  high light info  : old info
        // new user ---- List<User>


        //得到查询返回的内容
        List<SearchHit<CarES>> searchHits = search.getSearchHits();//getSearchHits();

        //设置一个最后需要返回的实体类集合
        List<CarES> carESList = new ArrayList<>();
        for(SearchHit<CarES> searchHit:searchHits){
            //高亮内容
            Map<String ,List<String>> highlightFields = searchHit.getHighlightFields();

            //将高亮的内容填充到content中
            String name = highlightFields.get("carName") ==null ?searchHit.getContent().getCarName() :highlightFields.get("carName").get(0);


            searchHit.getContent().setCarName(name );


            //放到实体类中
            carESList.add(searchHit.getContent());
        }
        System.out.println(carESList);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("carList",carESList);

        modelAndView.setViewName("vehicle/vehicle_screening");

        return modelAndView;
    }

    //根据订 单编号查出该订单
    @GetMapping("/getCarView")
    @ResponseBody
    public ModelAndView getCarsView(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("carsView",carServiceImpl.getCarView());
        mav.setViewName("vehicle/vehicle_screening");
        return mav;
    }

}
